package ms;

public class SingleObject {
    //
//    private static SingleObject instance = new SingleObject();
//
//    private SingleObject() {
//        // private constructor
//    }
//    public static SingleObject getInstance() {
//        return instance;
//    }
//    public void showMessage() {
//        System.out.println("展示 信息");
//    }
//}
//    private static SingleObject instance;
//
//    private SingleObject() {
//
//    }
//
//    public static SingleObject getInstance()  {
//        if (instance == null) {
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            instance = new SingleObject();
//        }
//        return instance;
//    }
//

    private static SingleObject instance;  // 添加 volatile 关键字

    private SingleObject() {}

    public static SingleObject getInstance() {
        if (instance == null) {
            synchronized (SingleObject.class) {
                if (instance == null) {
                    instance = new SingleObject();  // volatile 防止指令重排序
                }
            }
        }
        return instance;
    }

    public void showMessage() {
        System.out.println("展示 信息");
    }
}
